<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

/**
 * 导出 Excel，支持自定义表头顺序和标题
 *
 * @param string $filename   保存路径
 * @param array  $data       二维数组，键必须和 $headerRow 的键一致
 * @param array  $headerRow  表头映射：键 => 列标题
 */
function exportExcelWithHeader(string $filename, array $data, array $headerRow)
{
    if (empty($data)) {
        throw new InvalidArgumentException("数据为空，无法导出 Excel");
    }

    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();

    // 写表头（第 1 行）
    $col = 'A';
    foreach ($headerRow as $key => $title) {
        $sheet->setCellValue($col . '1', $title);
        $col++;
    }

    // 写数据
    $row = 2;
    foreach ($data as $item) {
        $col = 'A';
        foreach ($headerRow as $key => $title) {
            $value = $item[$key] ?? '';

            // 如果是时间戳（10位数字），转格式化时间
            if (is_numeric($value) && strlen((string)$value) === 10) {
                $value = date('Y-m-d H:i:s', $value);
            }

            // 如果是数组/对象（比如 EXIF 信息），转成 JSON
            if (is_array($value) || is_object($value)) {
                $value = json_encode($value, JSON_UNESCAPED_UNICODE);
            }

            $sheet->setCellValue($col . $row, $value);
            $col++;
        }
        $row++;
    }

    // 保存文件
    $writer = new Xlsx($spreadsheet);
    $writer->save($filename);

    echo "Excel 已生成: {$filename}\n";
}


//获取图片的exif信息
function getPhotoExif($photoPath){
	if (preg_match('/\.(jpg|jpeg|png|gif|webp)$/i', $photoPath)) {
		$exif = @exif_read_data($photoPath);
		if (!empty($exif['DateTime'])) {
			return $exif;
		}
	}
	return [];
}
//获取所有图片的EXIF信息
function getPhotoExifs($photoPaths){
	$exifs = [];
	foreach ($photoPaths as $key => $photoPath) {
		$exif = getPhotoExif($photoPath);
		if (!empty($exif)) {
			$exifs[] = $exif;
		}	
	}
	return $exifs;
}

//获取照片文件夹基础目录
$baseDir = dirname(__FILE__,2).DIRECTORY_SEPARATOR."照片".DIRECTORY_SEPARATOR;
$contrastPhotoDir = $baseDir."对照".DIRECTORY_SEPARATOR;
$deliverPhotoDir = $baseDir."交付".DIRECTORY_SEPARATOR;
//文件夹是否存在
if (!is_dir($contrastPhotoDir)) exit("对照照片文件夹不存在");
if (!is_dir($deliverPhotoDir)) exit("交付照片文件夹不存在");
//获取对照文件夹中的多个对比文件夹
$contrastPhotoDirs = glob($contrastPhotoDir."*",GLOB_ONLYDIR);
if (empty($contrastPhotoDirs)) exit("对照照片文件夹不存在");
//获取交付照片的exif信息
$deliverPhotoPaths = glob($deliverPhotoDir."*");
if (empty($deliverPhotoPaths)) exit("交付照片文件夹不能为空");
$deliverPhotoExifs = getPhotoExifs($deliverPhotoPaths);
//对交付照片的exif信息按照DateTime进行排序
usort($deliverPhotoExifs, function($a, $b) {
	$aTimeStamp = strtotime($a['DateTime']??"");
	$bTimeStamp = strtotime($b['DateTime']??"");
    if ( $aTimeStamp == $bTimeStamp) return 0;
    return ($aTimeStamp < $bTimeStamp) ? -1 : 1;
});

$headerRow = [
	"FileName"=>"压缩底片（非原始RAW版本）名称",
	"DateTime"=>"压缩底片（非原始RAW版本）最后修改时间"
];
foreach ($contrastPhotoDirs as $contrastPhotoDir) {
	$headerRow[basename($contrastPhotoDir).":DateTime"] = basename($contrastPhotoDir)."文件夹下该底片（非原始RAW版本）的最后修改时间";
}
$headerRow['origin'] = "压缩底片（非原始RAW版本）的EXIF信息";
foreach ($contrastPhotoDirs as $contrastPhotoDir) {
	$headerRow[basename($contrastPhotoDir).":origin"] = basename($contrastPhotoDir)."文件夹下该底片（非原始RAW版本）的EXIF信息";
}

$deliverPhotoExifs = array_map(function($exif)use($contrastPhotoDirs){
	$data = [];
	$data['FileName'] = $exif['FileName']??"";
	$data['DateTime'] = $exif['DateTime']??"";
	$data['origin'] = json_encode($exif,JSON_UNESCAPED_UNICODE+JSON_UNESCAPED_SLASHES+JSON_PRETTY_PRINT);
	foreach($contrastPhotoDirs as $contrastPhotoDir){
		$contrastPhotoDirBaseName = basename($contrastPhotoDir);
		$contrastPhotoPath = $contrastPhotoDir.DIRECTORY_SEPARATOR.$exif['FileName'];
		if (is_file($contrastPhotoPath)) {
			$contrastPhotoExif = getPhotoExif($contrastPhotoPath);
			$data[$contrastPhotoDirBaseName.":DateTime"] = $contrastPhotoExif["DateTime"]??"";
			$data[$contrastPhotoDirBaseName.":origin"] = @json_encode($contrastPhotoExif,JSON_UNESCAPED_UNICODE+JSON_UNESCAPED_SLASHES+JSON_PRETTY_PRINT)??"";
		}
	}
	return $data;
}, $deliverPhotoExifs);

exportExcelWithHeader(__DIR__.DIRECTORY_SEPARATOR.date("YmdHis")."照片对比.xlsx",$deliverPhotoExifs,$headerRow);
